
package uk.addie.mp3fixer.widget;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import org.jaudiotagger.tag.FieldKey;

import uk.addie.mp3fixer.MP3Handle;

public class MP3InfoWidget extends JPanel implements ActionListener {
    private static final long serialVersionUID = 1L;
    public MP3Handle          mTarget;
    Map<FieldKey, JTextField> buttons          = new HashMap<>();

    public MP3InfoWidget() {
        super();
        final LayoutManager layout = new GridBagLayout();
        final GridBagConstraints gbc = new GBCChain().gridY(0).anchor(GridBagConstraints.EAST);
        setLayout(layout);
        addTextField("Title", FieldKey.TITLE, gbc);
        addTextField("Album", FieldKey.ALBUM, gbc);
        addTextField("Artist", FieldKey.ARTIST, gbc);
        addTextField("Track", FieldKey.TRACK, gbc);
        addTextField("Disc", FieldKey.DISC_NO, gbc);
        addTextField("Year", FieldKey.YEAR, gbc);
        addTextField("Genre", FieldKey.GENRE, gbc);
        addTextField("Compilation", FieldKey.IS_COMPILATION, gbc);
    }

    @Override public void actionPerformed(final ActionEvent e) {
        for (final FieldKey fk : buttons.keySet()) {
            mTarget.setTag(fk, buttons.get(fk).getText());
        }
        if (mTarget.isChanged()) {
            mTarget.save();
        }
    }

    private void addTextField(final String description, final FieldKey fieldKey, final GridBagConstraints gbc) {
        final JTextField jtf = new JTextField();
        jtf.addActionListener(this);
        jtf.setToolTipText(description);
        jtf.setColumns(30);
        buttons.put(fieldKey, jtf);
        gbc.gridx = 0;
        add(new JLabel(description + " "), gbc);
        gbc.gridx = 1;
        add(jtf, gbc);
        gbc.gridy++;
    }

    public void clear() {
        mTarget = null;
        for (final FieldKey fk : buttons.keySet()) {
            buttons.get(fk).setText("");
        }
    }

    public void setMP3(final MP3Handle mp3) {
        mTarget = mp3;
        for (final FieldKey fk : buttons.keySet()) {
            buttons.get(fk).setText(mTarget.getTag(fk));
        }
    }
}
